import json
from datetime import datetime

from flask import Blueprint, render_template, request, current_app
import requests
from flask_login import current_user, login_required

from applications.common import curd
from applications.common.curd import model_to_dicts
from applications.common.helper import ModelFilter
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import xss_escape
from applications.extensions import db
from applications.models import Role

admin_prisoner_family = Blueprint('adminPrisonerFamily', __name__, url_prefix='/admin/prisoner_family')


# 获取体征设备管理页面
@admin_prisoner_family.get('/')
@login_required
def main():
    user_info=current_user
    access_time=datetime.now().strftime("%Y年%m月%d日 %H时%M分%S秒")
    return render_template('admin/prisoner_family/main.html', real_name=user_info.realname, access_time=access_time)


# 体征设备分页查询
@admin_prisoner_family.get('/data')
def data():
    page = request.args['page']
    page_size = request.args['limit']
    if 'content' not in request.args:
        content = ''
    else:
        content = request.args['content']
    response = requests.post(url=current_app.config['EMERGENCY_URL'] + '/prisoner_family',
                             headers={
                                 'Content-type': 'application/json'
                             },
                             data=json.dumps({
                                 "page": int(page) - 1,
                                 "page_size": page_size,
                                 "total_count": True,
                                 "search": content
                             }))
    data = json.loads(response.text)
    data['code'] = 0
    data['count'] = response.headers['Total-Count']
    data['limit'] = page_size
    return data


# 情景增加
@admin_prisoner_family.get('/add')
def add():
    roles = Role.query.all()
    return render_template('admin/prisoner_family/add.html', roles=roles)


@admin_prisoner_family.post('/save')
def save():

    req_json = request.json
    a = req_json.get("roleIds")
    code = xss_escape(req_json.get('code'))
    name = xss_escape(req_json.get('name'))
    sex = xss_escape(req_json.get('sex'))
    id_number = xss_escape(req_json.get('id_number'))
    phone = xss_escape(req_json.get('phone'))
    relation = xss_escape(req_json.get('relation'))
    address = xss_escape(req_json.get('address'))
    remark = xss_escape(req_json.get('remark'))
    prisoner_id = xss_escape(req_json.get('prisoner_id'))
    try:
        prisoner_id = int(prisoner_id)
    except:
        prisoner_id = None
    if sex==0 or sex=="0":
        sex="男"
    elif sex==1 or sex=="1":
        sex="女"
    else:
        sex="武装直升机"
    response = add_api(code, name, sex, id_number, phone, relation, address, remark, prisoner_id)
    if response['code']==200:
        return success_api(msg="增加成功")
    else:
        return fail_api(msg=response['message'])


def add_api(code, name, sex, id_number, phone, relation, address, remark, prisoner_id):
    body = {
        "code": code,
        "sex": sex,
        "name": name,
        "id_number": id_number,
        "phone": phone,
        "relation": relation,
        "address": address,
        "remark": remark,
        "prisoner_id": prisoner_id,
    }
    req = requests.post(url=current_app.config['EMERGENCY_URL'] + '/prisoner_family/create', json=body).json()
    return req

# 删除情景
@admin_prisoner_family.delete('/remove/<int:id>')
@authorize("admin:prisoner_family:remove", log=True)
def delete(id):
    body = {
        "ids": [id]
    }
    req = requests.post(url=current_app.config['EMERGENCY_URL'] + '/prisoner_family/delete', json=body).json()
    if req['code']==200:
        return success_api(msg="删除成功")
    else:
        return fail_api(msg=req['message'])


#  编辑情景
@admin_prisoner_family.get('/edit')
@authorize("admin:prisoner_family:edit", log=True)
def edit():
    prisoner_family=request.args.to_dict()
    if 'address' not in prisoner_family:
        address=[]
    else:
        address = prisoner_family['address'].split('-')
    if len(address)<4:
        prisoner_family['address_province']=''
        prisoner_family['address_city'] = ''
        prisoner_family['address_county'] = ''
        prisoner_family['address_detail'] = ''
    else:
        prisoner_family['address_province'] = address[0]
        prisoner_family['address_city'] = address[1]
        prisoner_family['address_county'] = address[2]
        prisoner_family['address_detail'] = address[3]

    roles = Role.query.all()
    checked_roles = []
    for r in roles:
        checked_roles.append(r.id)

    return render_template('admin/prisoner_family/edit.html', prisoner_family=prisoner_family, roles=roles, checked_roles=checked_roles)


#  编辑情景
@admin_prisoner_family.put('/update')
def update():
    req_json = request.json
    req_json['prisoner_id']=int(req_json['prisoner_id'])
    req = requests.post(url=current_app.config['EMERGENCY_URL']+'/prisoner_family/update', json=req_json).json()
    if req['code'] == 200:
        return success_api(msg="更新成功")
    else:
        return fail_api(msg=req['message'])


# 批量删除
@admin_prisoner_family.delete('/batchRemove')
@authorize("admin:prisoner_family:remove", log=True)
def batch_remove():
    ids = list(map(int, request.form.getlist('ids[]')))
    body = {
        "ids": ids
    }
    req = requests.post(url=current_app.config['EMERGENCY_URL'] + '/prisoner_family/delete', json=body).json()
    if req['code']==200:
        return success_api(msg="删除成功")
    else:
        return fail_api(msg=req['message'])